package com.caregiver.watch.common.utils.md5;


import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5工具类
 */
public class MD5Utils {


    private static final String UTF_8_ENCODING = "utf-8";
    private static final String MD5_ALGORITHM = "MD5";

    /**
     * 0
     */
    private static final String ZERO = "0";

    /**
     * MD5加密
     * @param str
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    public static String encode(String str) {
        try {
            MessageDigest md5 = MessageDigest.getInstance(MD5_ALGORITHM);
            byte[] bytes = md5.digest(str.getBytes(UTF_8_ENCODING));
            StringBuilder buf = new StringBuilder(StringUtils.EMPTY);
            int i;
            for (int offset = 0; offset < bytes.length; offset++) {
                i = bytes[offset] & 0xff;  // 使用位运算替代条件判断
                if (i < 16){
                    buf.append(ZERO);
                }
                buf.append(Integer.toHexString(i));
            }
            return buf.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return StringUtils.EMPTY;
        }
    }
}
